<template>
  <div class="md-ueditor-base">
    <iframe :src="`/iframeUeditor?type=${type}`" ref="uiframe" id="uiframe" frameborder="0" scrolling="none"></iframe>
  </div>
</template>

<script>
export default {
  name: 'MdUeditorBaseComponent',
  props: {
    value: [String],
    type: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      editorOptions: {
        editor: null
      },
      contentWindow: null,
      editorInterval: null
    }
  },
  watch: {
    value: {
      handler() {
        this.init()
      },
      deep: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    init() {
      const uiframe = this.$refs.uiframe
      if (uiframe) {
        uiframe.onload = () => {
          this.contentWindow = uiframe.contentWindow
          const editorOptions = this.contentWindow.editorOptions
          this.editorInterval = setInterval(() => {
            const editor = editorOptions.editor
            if (editor) {
              this.editorOptions.editor = editor
              if (this.value) {
                try {
                  editor.setContent(this.value)
                  clearInterval(this.editorInterval)
                } catch (error) {
                  console.log(error)
                }
              }
            }
          }, 200)
        }
      }
    },
    getContent() {
      if (this.contentWindow) {
        if (this.contentWindow.editorOptions.editor) {
          return this.contentWindow.editorOptions.editor.getContent()
        } else {
          return ''
        }
      } else {
        return ''
      }
    }
  }
}
</script>

<style lang="less" scoped>
.md-ueditor-base {
  width: 100%;
  height: 650px;
  overflow: hidden;
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-bottom: 1px solid #ccc;
  iframe {
    width: 100%;
    height: 650px;
  }
}
</style>
